#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Wed Jul 10 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
import base64
import datetime
import json
import logging
import os
import pathlib
import time

from third_api.ky import KYApi
from third_api.yb import YBApi

from .. import config, utils


class BaseHandler:
    yb_api = YBApi()
    ky_api = KYApi()
    MEDIA_UPLOADS_PATH = config.MEDIA_UPLOADS_PATH

    vin2vehicle_map = utils.bms_vehicle2gnss_vehicle_info()
    ky_vehicles = ky_api.get_vehicles()

    logger = utils.get_logger('kaiyi-handlers')

    imei2vehicle_info_map = {}
    for _, v in vin2vehicle_map.items():
        imei2vehicle_info_map[v['imei']] = v

    def not_exist_add_vehicle(self, device_id):
        if device_id not in self.imei2vehicle_info_map:
            self.ky_vehicles = self.ky_api.get_vehicles()
            vehicle = self.ky_vehicles[device_id]
            res = self.yb_api.add_vehicle(vehicle).json()
            self.imei2vehicle_info_map[device_id] = {
                'terminal_id': res['terminal']['id'],
                'vehicle_id': res['vehicle']['id'],
                'company_id': res['company']['id'],
                'license_number': res['vehicle']['license_number'],
                'vin': res['vehicle']['vin'],
                'device_id': res['terminal']['imei'],
                'imei': res['terminal']['imei']
            }
        return self.imei2vehicle_info_map[device_id]['vehicle_id']

    def timespan2str(self, ts):
        return datetime.datetime.fromtimestamp(int(ts)).strftime('%Y-%m-%d %H:%M:%S')

    def transform_speed(self, ky_speed):
        # 速度转换
        if ky_speed:
            #  m/s ->km/h
            speed = round(float(ky_speed) / 100 * 3.6, 2)
        else:  # speed 可能为空字符串
            speed = 0
        return speed
